package com.wxl.asmgradleplugin.myplugin

import javassist.ClassPool
import org.gradle.api.artifacts.transform.InputArtifact
import org.gradle.api.artifacts.transform.TransformAction
import org.gradle.api.artifacts.transform.TransformOutputs
import org.gradle.api.artifacts.transform.TransformParameters
import org.gradle.api.file.FileSystemLocation
import org.gradle.api.provider.Provider
import java.io.File
import java.io.FileInputStream

abstract class DirInstrumentTransform : TransformAction<TransformParameters.None> {

    @get:InputArtifact
    abstract val inputDir: Provider<FileSystemLocation>

    override fun transform(outputs: TransformOutputs) {
        val input = inputDir.get().asFile
        println("===444 input ${input.absolutePath}")
        val output = outputs.dir(input.nameWithoutExtension)
        val pool = ClassPool.getDefault()

        input.walkTopDown().forEach { file ->
            if (file.isFile) {
                println("===444 ${file.absolutePath}")
                val relativePath = file.relativeTo(input).path
                val outFile = File(output, relativePath).apply { parentFile.mkdirs() }

                if (file.extension == "class") {
                    val classBytes = FileInputStream(file).readBytes()
                    val ctClass = pool.makeClass(classBytes.inputStream())

                    if (!ctClass.isFrozen && !ctClass.isInterface) {
                        ctClass.declaredConstructors.forEach { constructor ->
                            constructor.insertBefore("""System.out.println(">>> DIR Constructor called");""")
                        }
                        ctClass.writeFile(output.absolutePath)
                        ctClass.detach()
                    } else {
                        outFile.writeBytes(classBytes)
                    }
                } else {
                    file.copyTo(outFile, overwrite = true)
                }
            }
        }
    }
}
